package com.mobile.check.present;

import android.os.Environment;
import android.text.TextUtils;

import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NToast;
import cn.droidlover.xdroidmvp.mvp.IView;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import cn.droidlover.xdroidmvp.net.NetError;
import io.reactivex.functions.Consumer;
import com.mobile.check.activitys.GlobalPoolApplication;
import com.mobile.check.beans.CheckItemInfo;
import com.mobile.check.db.EntityManager;
import com.mobile.check.net.BaseObjBean;
import com.mobile.check.util.AppContents;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class BasePresent<V extends IView> extends XPresent<V> {
    public Consumer failConsumer;
    public Consumer failNeedLoginConsumer;
    public Consumer failNotDealConsumer;

    public BasePresent() {
        failConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                if (throwable != null && throwable instanceof NetError) {
                    dealFailResult((NetError) throwable);
                }
                throwable.printStackTrace();
                getV().disLoadDialog();
                getV().loadFail();
            }
        };
        failNeedLoginConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) {
                e.printStackTrace();
                NetError error = null;
                if (e != null) {
                    if (!(e instanceof NetError)) {
                        if (e instanceof UnknownHostException) {
                            error = new NetError("请检查网络连接", NetError.NoConnectError);
                        } else if (e instanceof JSONException
                                || e instanceof JsonParseException
                                || e instanceof JsonSyntaxException) {
                            error = new NetError(e, NetError.ParseError);
                        } else if (e instanceof ConnectException) {
                            error = new NetError("请检查网络连接", NetError.NoConnectError);
                        } else {
                            error = new NetError(e, NetError.ParseError);
                        }
                    } else {
                        error = (NetError) e;
                    }
                    dealFailResult(error);
                }
                getV().disLoadDialog();
                getV().loadFail();
            }
        };
        failNotDealConsumer = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {

            }
        };
    }

    public Consumer getFailNeedLoginConsumer() {
        return failNeedLoginConsumer;
    }

    public void dealFailResult(NetError error) {
        error.printStackTrace();
        if (error.getType() == NetError.AuthError) {
            SharedPref.getInstance(GlobalPoolApplication.getContext()).putString(AppContents.TOKEN, "");
            getV().toLogin();
        } else {
            String message = error.getMessage();
            if (!TextUtils.isEmpty(message)) {
                NToast.shortToast(message);
            }
        }
    }


    public abstract class SuccessConsumer<T> implements Consumer<BaseObjBean> {
        @Override
        public void accept(BaseObjBean objBean) {
            getV().disLoadDialog();
            getV().showMainView();
            T t = (T) objBean.getData();
            accept2(t);
        }

        public abstract void accept2(T t);
    }

    public abstract class SuccessConsumer2<T> implements Consumer<BaseObjBean> {
        @Override
        public void accept(BaseObjBean objBean) {
            getV().disLoadDialog();
        }

    }


    public String getToken() {
        String token = SharedPref.getInstance(GlobalPoolApplication.getContext()).getString(AppContents.TOKEN, "");
        return token;
    }

    public boolean isLogin() {
        return !TextUtils.isEmpty(getToken());
    }

    public static MultipartBody filesToMultipart2Body(List<String> list) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (String path : list) {
            File file = new File(path);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            builder.addFormDataPart(file.getName(), file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    public static MultipartBody filesToMultipartBody(String token, String path, String fileType) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(path);
        String mediaType;
        switch (fileType) {
            case "xls":
                mediaType = "application/x-xls";
                break;
            case "zip":
                mediaType = "application/zip";
                break;
            case "jpeg":
                mediaType = "image/jpeg";
                break;
            default:
                mediaType = "application/octet-stream";
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse(mediaType), file);
        builder.addFormDataPart("file", file.getName(), requestBody);
        builder.addFormDataPart("token", token);
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    public void saveCrash(String content) {
        String sRoot = Environment.getExternalStorageDirectory().getAbsolutePath();//获取跟目录
        String targetDir = sRoot + "/检测系统/错误日志";
        long time = Calendar.getInstance().getTimeInMillis();
        String fileName = Kits.Date.getYmdhms(time) + ".txt";
        Kits.File.writeFile(targetDir + File.separator + fileName, content);
    }
    public void saveLog(String fileName,String content,boolean deleteBefore) {
        String sRoot = Environment.getExternalStorageDirectory().getAbsolutePath();//获取跟目录
        String targetDir = sRoot + "/检测系统/保存日志";
        fileName = fileName + ".txt";
        File file = new File(targetDir + File.separator + fileName);
        if (deleteBefore) {
            Kits.File.deleteFile(file.getPath());
        }
        Kits.File.writeFile(targetDir + File.separator + fileName, content,true);
    }

    public void saveLog(String fileName,String content) {
       saveLog(fileName,content,false);
    }

    public void saveCrash(String fileName, Throwable throwable) {
        Map<String, String> infos = new HashMap<String, String>();
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        throwable.printStackTrace(printWriter);
        Throwable cause = throwable.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);


        String sRoot = Environment.getExternalStorageDirectory().getAbsolutePath();//获取跟目录
        String targetDir = sRoot + "/检测系统/错误日志";
        fileName = fileName + ".txt";
        File file = new File(targetDir + File.separator + fileName);
        Kits.File.writeFile(targetDir + File.separator + fileName, sb.toString(),true);
    }


    public CheckItemInfo getScanResultByID(long id){
        CheckItemInfo itemInfo =EntityManager.getInstance().getScanResultByID(id);
        return itemInfo;
    }
}
